<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\models\Tag;
use application\utilities\Utility;
class LinearContentRelation extends DataType {
	public static $name = 'Linear Content Relation';
	public static $fields = array();
	
	public static function validate($field, $data, $results) {
		$relation = getFieldMetaData($field->cf_id, 'relation');
		if($field->cf_required && !$data['relations_'.$field->cf_id]) {
			$results['errors'][] = $field->cf_display_name.' is required.';
		}
		else {
			$results['db_fields']['relations'][$relation] = $data['relations_'.$field->cf_id];
		}
		
		return $results;
	}
	
	public static function formHeader($field) {
		Modulator()->includeScript('jquery');
		Modulator()->includeScript(getCommonFile('concerto/javascript/content-relation.js'));
		?>
		<script type="text/javascript">
			$(document).ready(function() {
				$('#relations_<?=$field->cf_id?>').linearContentRelation();
			});
		</script>
		<?php
	}
	
	public static function display($formElements) {
		if($formElements['elements']['element']) :
			?>
			
			<fieldset class="relation-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php
			echo $formElelements['elements']['search'];
			echo $formElements['elements']['element'];?>
			</section>
			</fieldset>
		<?php endif;
	}
	
	public static function build($field, $data) {
		// Get field meta data
		$relation = getFieldMetaData($field->cf_id, 'relation');
		//$display = getFieldMetaData($field->cf_id, 'display');
		
		$contentId = $data['content_id'];
		

		
		if($data['relations['.$field->cf_id.']']) {
			$relations = $data['relations['.$field->cf_id.']'];
		}
		else {
			$relations = DB()->getResults("SELECT `cn_content_content_relations`.*, `a`.`content_title` AS `content1`, `a`.`content_id` AS `content1_id`, `b`.`content_title` AS `content2`, `b`.`content_id` AS `content2_id` FROM `cn_content_content_relations` INNER JOIN `cn_content` `a` ON `a`.`content_id`=`ccr_content1` INNER JOIN `cn_content` `b` ON `b`.`content_id`=`ccr_content2` WHERE `ccr_relation`='$relation' AND (`ccr_content1`='$contentId' OR `ccr_content2`='$contentId')");
		}
		
		/** Display relations */
		$formElements = array('column'=>'relation_'.$relation, 'display'=>$field->cf_display_name, 'data_type'=>'ContentRelation', 'elements'=>array());
	
		
		$existingSecondaryContents = $data['relations_'.$field->cf_id];
		if(!$existingSecondaryContents) $existingSecondaryContents = array();
		// Get available content for this relation
		$row = DB()->getRow("SELECT * FROM `cn_content_relation_types` WHERE `crt_id`='$relation'");
		if($row->crt_type1 == $field->cf_content_type) {
			$secondaryType = $row->crt_type2;
		}
		else {
			$secondaryType = $row->crt_type1;
		}
		
		// Check for fellow children
		$fellowChildren = getFieldMetaData($field->cf_id, 'fellow_children');
		if($fellowChildren) {
			$contentParent = " AND `content_parent`='".$data['content_parent']."'";
		}
		else {
			$contentParent = '';
		}
		$attachableContent = DB()->getResults("SELECT * FROM `cn_content` WHERE `content_type`='$secondaryType'$contentParent ORDER BY `content_title`");
		$contentSelect = '<select data-content-type="'.$secondaryType.'" multiple="multiple" class="content-relation" name="relations_'.$field->cf_id.'[]" id="relations_'.$field->cf_id.'">';
		
		foreach($attachableContent as $content) {
			if(in_array($content->content_id, $existingSecondaryContents)) 
				$contentSelect .= '<option selected="selected" value="'.$content->content_id.'">'.$content->content_title.'</option>';
			else
				$contentSelect .= '<option value="'.$content->content_id.'">'.$content->content_title.'</option>';
		}
		
		$contentSelect .= '</select>';
		$formElements['elements']['element'] = $contentSelect;
		
		
		return $formElements;
	
	}
	
	public static function save() {
		$field = $_REQUEST['field'];
		foreach($_REQUEST as $key=>$value) {
			if(substr($key, 0, 5) == 'meta_') {
				$varname = substr($key, 5);
				$count = DB()->getCount("SELECT * FROM `cn_field_meta` WHERE `cfm_key`='$varname' AND `cfm_field`='$field'");
				if(!$count) {
					$insert = array('cfm_key'=>$varname, 'cfm_value'=>$value, 'cfm_field'=>$field);
					DB()->insert('cn_field_meta', $insert);
				}
				else {
					DB()->query("UPDATE `cn_field_meta` SET `cfm_value`='$value' WHERE `cfm_key`='$varname' AND `cfm_field`='$field'");
				}
			}
		}
	}
	
	public static function endForm($field, $data, $id, $type) {
		$relationID = getFieldMetaData($field->cf_id, 'relation');
		$relations = $data['relations'][$relationID];
		if(!$relations) $relations = array();
		
		
		
		$existing = DB()->getResults("SELECT `cn_content_content_relations`.*, `a`.`content_title` AS `content1`, `a`.`content_id` AS `content1_id`, `b`.`content_title` AS `content2`, `b`.`content_id` AS `content2_id` FROM `cn_content_content_relations` INNER JOIN `cn_content` `a` ON `a`.`content_id`=`ccr_content1` INNER JOIN `cn_content` `b` ON `b`.`content_id`=`ccr_content2` WHERE `ccr_relation`='$relationID' AND (`ccr_content1`='$id' OR `ccr_content2`='$id')");
		
		// Get relations
		$currentRelations = array();
		foreach($existing as $relation) {
			if($relation->content1_id == $id) {
				$currentRelations[$relation->ccr_id] = $relation->content2_id;
			}
			else {
				$currentRelations[$relation->ccr_id] = $relation->content1_id;
			}
		}
		// Get relations that we don't have to add
		$noNeed = array_intersect($relations, $currentRelations);
		
		// Get relations we need to remove
		$toDelete = array_keys(array_diff($currentRelations, $noNeed));
		$toDelete = "'".implode("', '", $toDelete)."'";
		
		// Get tags we need to add
		$toAdd = array_diff($relations, $currentRelations);
		

		
		DB()->query("DELETE FROM `cn_content_content_relations` WHERE `ccr_id` IN ($toDelete) AND (`ccr_content1`='$id' OR `ccr_content2`='$id')");
		foreach($toAdd as $add) {
			DB()->insert('cn_content_content_relations', array('ccr_content1'=>$id, 'ccr_content2'=>$add, 'ccr_relation'=>$relationID));
		}
	}
	
	public static function fromDB($fields, $field, $data) {
		$column = $field->cf_column;
		$contentId = $data['content_id'];
		$relation = getFieldMetaData($field->cf_id, 'relation');
		$relations = DB()->getResults("SELECT `cn_content_content_relations`.*, `a`.`content_title` AS `content1`, `a`.`content_id` AS `content1_id`, `b`.`content_title` AS `content2`, `b`.`content_id` AS `content2_id` FROM `cn_content_content_relations` INNER JOIN `cn_content` `a` ON `a`.`content_id`=`ccr_content1` INNER JOIN `cn_content` `b` ON `b`.`content_id`=`ccr_content2` WHERE `ccr_relation`='$relation' AND (`ccr_content1`='$contentId' OR `ccr_content2`='$contentId')");
		
		// Get relations
		$existingSecondaryContents = array();
		foreach($relations as $existing) {
			if($existing->content1_id == $contentId) {
				$existingSecondaryContents[] = $existing->content2_id;
			}
			else {
				$existingSecondaryContents[] = $existing->content1_id;
			}
		}

		return array('relations_'.$field->cf_id => $existingSecondaryContents);
	}
	
	public static function editForm($field) {
		?>
			<input type="hidden" name="field_id" value="<?=$field->getId()?>"/>
			<ul class="form-fields">
			<li>
			<label>Field Display Name</label>
			<input type="text" name="field_display_name" class="big wide" value="<?=$field->getDisplayName()?>"/>
			</li>
			<li>
			<label>Field Description</label>
			<textarea name="field_description" class="wide"><?=$field->getDescription()?></textarea>
			</li>
			<li>
				<label>Relation</label>
				<?php $field->getMeta('relation');?>
				<select name="meta_relation">
					<?php $relations = DB()->getResults("SELECT * FROM `cn_content_relation_types` WHERE (`crt_type1`='".$field->getContentType()."' OR `crt_type2`='".$field->getContentType()."') AND `crt_relation_type` != 'three way'");
					foreach($relations as $relation) : ?>
					<option <?= ($field->getMeta('relation') == $relation->crt_id) ? 'selected="selected"' : ''?> value="<?=$relation->crt_id?>"><?=$relation->crt_name?></option>
					<?php endforeach;?>
				</select>
			</li>
			<li>
				<label><input type="checkbox" name="meta_fellow_children" value="TRUE" <?=($field->getMeta('fellow_children')) ? 'checked="checked"' : ''?>/> Choose from only fellow children of the parent (if applicable)</label>
			</li>
			
			</ul>
			<?php
	}	
	
	public static function prepareData($field, $data, $params) {
		$relations = Utility::sqlImplodedArray($data['relations_'.$field->cf_id]);
		$contents = DB()->getVarArray("SELECT * FROM `cn_content` WHERE `content_id` IN ($relations)");
		
		$return = array();
		foreach($contents as $content) {
			$return[] = new \application\models\Content('id='.$content);
		}
		
		return $return;
	}
	
}
?>